using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApiDemo.Application.Common.Interface;
using ApiDemo.Application.ReqDto;
using ApiDemo.Application.ResDto;
using ApiDemo.Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ApiDemo.Api.Controllers
{
    [Authorize]
    public class AuthorizationController : ControllerBase
    {
        private readonly IIdentityService _identityService;
        private readonly IRepository<AppUser> _appUserRespository;
        public AuthorizationController(IIdentityService identityService,IRepository<AppUser> appUserRespository)
        {
            _identityService = identityService;
            _appUserRespository=appUserRespository;
        }

        [AllowAnonymous]
        [HttpPost("login")]
        public async Task<IActionResult> Authenticate([FromBody] UserForAuth userForAuth)
        {
            if (!_identityService.ValidateUserAsync(userForAuth))
            {
                return Unauthorized();
            }

            return Ok(new { Token = await _identityService.GenerateToken() });
        }

        [AllowAnonymous]
        [HttpPost("refresh")]
        public async Task<IActionResult> RefreshToken([FromBody] AppToken appToken)
        {
            var tokenToReturn = await _identityService.RefreshTokenAsync(appToken);
            return Ok(tokenToReturn);
        }

        [HttpPost("/users")]
        public async Task<AppUser> CreateUser([FromBody] UserForAuth userForAuth)
        {
            var tx=await _appUserRespository.AddAsync(new AppUser{Username=userForAuth.Username,Password=userForAuth.Password});
            return tx;
        }
    }
}